<script setup>
import {onMounted, ref} from "vue";
import {
  addUserService,
  deleteUserService,
  deleteUsersService,
  exportUserDataService,
  getUserPageService,
  updateUserService,
  updateUserStatusService
} from '../api/user.js'
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";

const username = ref('')
const phone = ref('')
const email = ref('')
const pageNum = ref(1)
const pageSize = ref(5)
const tableData = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const user = JSON.parse(localStorage.getItem('user'))
const token = user?.token
const userForm = ref({
  username: '',
  name: '',
  phone: '',
  email: '',
  userType: 1,
  status: 0,
})
const rules = {
  name: [
    {required: true, message: '姓名不能为空', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {min: 8, max: 16, message: '用户名长度应在 8 ~ 16 位之间', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {min: 6, max: 32, message: '邮箱长度应在 6 ~ 32 位之间', trigger: 'blur'},
    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  userType: [
    {required: true, message: '用户类型不能为空', trigger: 'change'},
    {type: 'number', min: 0, max: 2, message: '用户类型取值范围：0-系统管理员，1-普通用户，2-访客', trigger: 'change'}
  ],
};
const formRef = ref();
const avatarUrl = ref('')

const emit = defineEmits(['updateUser'])

// 用户列表
const userList = async () => {

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    username: username.value ? username.value : null,
    phone: phone.value ? phone.value : null,
    email: email.value ? email.value : null
  }
  let res = await getUserPageService(params)
  tableData.value = res.data.data?.list
  total.value = parseInt(res.data.data?.total)

}

// 页面加载时获取用户列表
onMounted(() => {
  userList();
});

// 修改状态
const handleStatusChange = async (value, row) => {
  await updateUserStatusService({username: row.username, status: value})
};

// 重置
const refresh = async () => {
  username.value = ''
  phone.value = ''
  email.value = ''
  await userList()
}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  userList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  userList();
};

// 删除用户
const deleteHandle = (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteUserService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await userList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

// 表格行数据
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 批量删除
const handleDeleteBatch = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的用户");
    return;
  }

  const ids = selectedRows.value.map(item => item.id)

  ElMessageBox.confirm(
      '当前操作将永久删除选中的用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteUsersService(ids);
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await userList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    userList()
    ElMessage.info('取消删除');
  });
}

// 打开弹窗
const handleOpenDialog = (row) => {
  if (row.id) {
    dialogTitle.value = '修改用户'
    userForm.value = {...row}
    avatarUrl.value = row.avatar
  } else {
    dialogTitle.value = '新增用户'
    userForm.value = {
      username: '',
      name: '',
      phone: '',
      email: '',
      userType: 1,
      status: 0,
    }

    avatarUrl.value = ''
  }
  dialogVisible.value = true
}

// 新增用户
const handleAddUser = async () => {
  const res = await addUserService(userForm.value)

  if (res.data.code === "200") {
    ElMessage.success("新增成功")
    dialogVisible.value = false
    await userList()
  } else {
    ElMessage.error(res.data.message)
  }
}

// 修改用户
const handleUpdateUser = async () => {
  const res = await updateUserService(userForm.value)
  if (res.data.code === "200") {
    ElMessage.success("修改成功")
    dialogVisible.value = false
    let token = JSON.parse(localStorage.getItem('user')).token
    let user = {
      username: userForm.value.username,
      name: userForm.value.name,
      phone: userForm.value.phone,
      email: userForm.value.email,
      userType: userForm.value.userType,
      status: userForm.value.status,
      avatar: userForm.value.avatar,
      token: token
    }
    emit('updateUser', user)

    await userList()
  } else {
    ElMessage.error(res.data.message)
  }
}

// 保存用户
const handleSaveUser = async () => {
  const valid = await formRef.value.validate().catch(() => false);
  if (valid) {
    if (userForm.value.avatar) {
      if (userForm.value.id) {
        await handleUpdateUser();
      } else {
        await handleAddUser();
      }
    } else {
      ElMessage.error('请上传头像')
    }

  } else {
    ElMessage.error("请填写完整信息")
  }
}

// 导出用户数据
const handleExportUserData = async () => {
  try {
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning("当前无数据可导出");
      return;
    }
    await exportUserDataService({
      username: username.value ? username.value : null,
      phone: phone.value ? phone.value : null,
      email: email.value ? email.value : null,
      ids: selectedRows.value.map(item => item.id) ? selectedRows.value.map(item => item.id) : null
    })
    ElMessage.success("导出成功")
  } catch (error) {
    ElMessage.error("导出失败")
  }
}

// 上传文件前检查
const beforeUpload = (file) => {
  const isValidFormat = /\.(xlsx|xls)$/.test(file.name);
  if (!isValidFormat) {
    ElMessage.error("只能上传 Excel 文件");
    return false;
  }
  return true;
};

// 上传文件成功
const handleSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("导入成功" || response.message);
    userList();
  } else {
    ElMessage.error(response.message);
  }
};

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isValidFormat = /\.(jpg|jpeg|png)$/i.test(file.name);
  const isValidSize = file.size / 1024 / 1024 < 2; // 小于 2MB

  if (!isValidFormat) {
    ElMessage.error('只能上传 JPG/JPEG/PNG 格式的图片');
    return false;
  }

  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }

  return true;
};

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("上传成功");
    userForm.value.avatar = response.data;
    avatarUrl.value = response.data;
    userList();
  } else {
    ElMessage.error(response.message);
  }
};


</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="username" clearable style="width: 240px" placeholder="请输入用户名"/>
      <el-input v-model="phone" clearable style="width: 240px; margin: 0 20px" placeholder="请输入手机号"/>
      <el-input v-model="email" clearable style="width: 240px" placeholder="请输入邮箱"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="userList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" icon="DocumentAdd" @click="handleOpenDialog">新增用户</el-button>
      <el-button type="danger" style="margin-left: 0" icon="Delete" @click="handleDeleteBatch">批量删除</el-button>
      <el-upload
          ref="uploadRef"
          :headers="{ Authorization: token }"
          action="http://127.0.0.1:9090/api/user/import"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload">
        <el-button type="success" icon="Download">导入数据</el-button>
      </el-upload>
      <el-button type="info" icon="Upload" @click="handleExportUserData">导出数据</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column fixed="left" type="selection" align="center" width="55"/>
        <el-table-column prop="avatar" align="center" label="头像" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.avatar" :src="scope.row.avatar" fit="cover"
                      :preview-src-list="[scope.row.avatar]" :preview-teleported="true"
                      style="width: 50px; height: 50px; border-radius: 50%">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="username" align="center" label="用户名"/>
        <el-table-column prop="name" align="center" label="姓名"/>
        <el-table-column prop="phone" align="center" label="手机号"/>
        <el-table-column prop="email" align="center" label="邮箱"/>
        <el-table-column prop="userType" align="center" label="角色" width="100">
          <template #default="scope">
            <el-text v-if="scope.row.userType === 0" type="primary">{{ ['管理员', '普通用户', '访客'][scope.row.userType] }}</el-text>
            <el-text v-if="scope.row.userType === 1" type="success">{{ ['管理员', '普通用户', '访客'][scope.row.userType] }}</el-text>
            <el-text v-if="scope.row.userType === 2" type="info">{{ ['管理员', '普通用户', '访客'][scope.row.userType] }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" label="状态" width="100">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="(value) => handleStatusChange(value, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="handleOpenDialog(scope.row)" icon="Edit">修改</el-button>
            <el-button type="danger" icon="Delete" @click="deleteHandle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 新增 / 修改 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" align-center width="500" destroy-on-close>
    <el-form :model="userForm" :rules="rules" ref="formRef" label-width="80px"
             style="padding: 0 50px 0 0">
      <el-form-item class="el-form-item-avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:9090/api/file/upload"
            :show-file-list="false"
            :headers="{ Authorization: token }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="avatarUrl" alt="图像无法加载" :src="avatarUrl" style="width: 120px; height: 120px" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username" class="el-form-item">
        <el-input disabled v-model="userForm.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="姓名" prop="name" class="el-form-item">
        <el-input v-model="userForm.name" placeholder="请输入姓名"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone" class="el-form-item">
        <el-input v-model="userForm.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" class="el-form-item">
        <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="角色" prop="userType" class="el-form-item">
        <el-select v-model="userForm.userType" style="width: 100%">
          <el-option label="管理员" :value="0"/>
          <el-option label="普通用户" :value="1"/>
          <el-option label="访客" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" class="el-form-item">
        <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

:deep(.avatar-uploader .el-upload) {
  width: 120px;
  height: 120px;
  border: 2px dashed var(--el-border-color);
  cursor: pointer;
  display: flex;
  border-radius: 20px;
  align-items: center;
  justify-content: center;
  position: relative;
  left: 90px;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin: 0 auto;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  padding: 5px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

</style>